#include "../BBE.h"
#include "../Framework.h"
#include "../Image/ImageLib.h"
using namespace ImageLib;
BOOL CALL GfxInit(HWND hWnd,int nWidth,int nHeight)
{
	return g_PaintClass->InitPaint(hWnd,nWidth,nHeight);
}
void CALL GfxClear(DWORD dwColor)
{
	g_PaintClass->Clear(dwColor);
}
void CALL GfxBegin()
{
	g_PaintClass->Clear();
}
void CALL GfxEnd()
{
	if (IsIconic(GfxGetHwnd())) return ;
	if (g_PaintClass->IsDirty())
	{
		size_t size = g_PaintClass->GetRenderSize();
		RENDLIST RenderList = g_PaintClass->GetRenderList();
		for (size_t i=0;i<size;i++)
		{
			RECT rcDraw,rcQuad;
			GuiInfo* texture = RenderList[i];
			HGUI pChild= (HGUI)texture->dwHandle;
			int left = pChild->GetWorldPos().x;
			int top = pChild->GetWorldPos().y;
			int right = left+pChild->GetWidth();
			int bottom = top + pChild->GetHeight();
			SetRect(&rcQuad,left,top,right,bottom);
			RECT WndRect = g_PaintClass->GetDirtyRect();
			if (IntersectRect(&rcDraw,&rcQuad,&WndRect))
			{
				int tx = 0;
				int ty = 0;
				int tw = 0;
				int th = 0;
				HTEXTURE stResTex = NULL;
				if (pChild->GetCreateMedthod() == GCM_CREATE || pChild->GetCreateMedthod() == GCM_NULL)
				{
					continue;
				}
				else if (pChild->GetCreateMedthod() == GCM_TEXTURE)
				{
					stResTex = (HTEXTURE)pChild->GetTexture();
				}
				else if (pChild->GetCreateMedthod() == GCM_ANIMATION)
				{
					tagAniData* m_aniData = texture->AniData;
					UINT nFrame = pChild->GetCurFrame();
					stResTex = (HTEXTURE)m_pResManager->GetTexPtrFromID((m_aniData->AniItemArray[nFrame])->ResID);
					tx = (m_aniData->AniItemArray[nFrame])->tx;
					ty = (m_aniData->AniItemArray[nFrame])->ty;
					tw = (m_aniData->AniItemArray[nFrame])->tw;
					th = (m_aniData->AniItemArray[nFrame])->th;
				}
				int nStartX = rcDraw.left;
				int nStartY = rcDraw.top;
				int nBmpX = tx;
				int nBmpY = ty;
				int nBmpW = rcDraw.right - rcDraw.left;
				int nBmpH = rcDraw.bottom - rcDraw.top;
				if (rcQuad.left < WndRect.left)
					nBmpX += (WndRect.left - rcQuad.left);
				if (rcQuad.top <WndRect.top)
					nBmpY += (WndRect.top - rcQuad.top);
				g_PaintClass->AlphaBlt(nStartX,nStartY,stResTex,255,nBmpX,nBmpY,nBmpW,nBmpH);
			}
		}
		RECT DirtyRect = g_PaintClass->GetDirtyRect();
		int dx = DirtyRect.left;
		int dy = DirtyRect.top;
		int sx = DirtyRect.left;
		int sy = DirtyRect.top;
		int sw = DirtyRect.right - DirtyRect.left;
		int sh = DirtyRect.bottom - DirtyRect.top;
		g_PaintClass->BitBltToDC(0,0,0,0,640,480);
		g_PaintClass->SetRectEmpty();
	}
}
void CALL GfxPresent(int nDestX,int nDesty,int nBackX,int nBackY,int nBackW,int nBackH)
{
	g_PaintClass->BitBltToDC(nDestX,nDesty,nBackX,nBackY,nBackW,nBackH);
}
HWND CALL GfxGetHwnd()
{
	return g_PaintClass->GetHWND();
}
void CALL GfxDirty(RECT& rcDirty)
{
	g_PaintClass->SetDirty(rcDirty);
}
